<template>
  <XLayoutMain class="adv-create-form" ref="layoutMainRef">
    <n-grid x-gap="12" :cols="2">
      <n-gi>
        <n-space vertical>
          <!-- <account-check ref="account" /> -->
          <!--  -->
          <!-- 账户选择 -->
          <account-select ref="accountSelectRef" :index="0" @update="accountUpdateHandle"
            @remove="accountRemoveHandle"></account-select>
          <!-- 营销内容 -->
          <market-content ref="markContent" @targetTypeChange="targetTypeChange" :index="1"></market-content>
          <!-- <Step1 ref="step1" @changeAccount="getAccountCode" /> -->
          <!-- 商品库 -->
          <product-check ref="productRef" v-if="market.marketingTargetType === 'MARKETING_TARGET_TYPE_CONSUMER_PRODUCT'"
            :index="2" />
          <!-- 定向 -->
          <Step3 ref="advDiectRef" :index="3" />
          <!-- <Step4 ref="step4" /> -->
          <!-- 版位 -->
          <AdvPosition ref="advPositionRef" :index="4" />
        </n-space>
      </n-gi>
      <n-gi>
        <n-space vertical>
          <Step5 ref="schedulePriceRef" :index="5" />
          <!-- <Step6 ref="step6" /> -->
          <CreativeWay :index="6" />
          <CreativeContent v-if="creativor.hasMediaOrText" ref="creativeContentRef" :key="adv.creativor.uuid"
            :index="7" />
          <MarkComponent ref="markComponentRef" :index="8"></MarkComponent>
          <LoadPage ref='loadPageRef' :index="9"></LoadPage>
          <!-- <Step7 ref="step7" :params="creativeInfo" /> -->
        </n-space>
      </n-gi>
    </n-grid>
    <template #footer>
      <n-space justify="center">
        <x-button :loading="saveLoading" type="default" @click="handleBack">返回</x-button>
        <x-button :loading="saveLoading" type="primary" @click="handleSave">保存</x-button>
      </n-space>
    </template>
  </XLayoutMain>
</template>

<script setup lang="ts">
import { XLayoutMain, XButton } from '@/components'
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router'
import {
  Step3,
  Step5,
  AccountSelect,
  MarketContent,
  CreativeWay,
  AdvPosition,
  CreativeContent,
  MarkComponent
} from './components'
import LoadPage from './components/load-page.vue'
import { computed, nextTick, onMounted, provide, ref, onBeforeMount } from 'vue'
import { NGrid, NGi, NSpace, useMessage } from 'naive-ui'
import { useStore } from '@/store'
import ProductCheck from '@/views/advertising/ads/create/components/product-check.vue';
import Account from '@/store/modules/adv/account'
import { createAdvBody } from '@/store/modules/adv/helper';
import { saveAdv } from '@/api/intelligent'
import { useAdgroupname } from '@/store/modules/adv/hooks/useAdgroupname'
const router = useRouter()
const route = useRoute()
const store = useStore()
const message = useMessage();
const adv = computed(() => store.state.adv.modal);
const creativor = computed(() => store.state.adv.modal.creativor);
const market = computed(() => adv.value.market)
const layoutMainRef = ref();

nextTick(() => {
  const container = layoutMainRef.value;
  store.commit('adv/SET_SCROLLER', container.scrollerRef);
})


const isEdit = computed(() => {
  return !!route.query.id
})


const saveLoading = ref(false)

// 各模块 -------
const accountSelectRef = ref();
const advDiectRef = ref();
const schedulePriceRef = ref();
const productRef = ref();
const creativeContentRef = ref();
const advPositionRef = ref();
const loadPageRef = ref();
const markComponentRef = ref();

function accountUpdateHandle() {
  productRef.value.defaultAction();
  advDiectRef.value.defaultAction();
  advPositionRef.value.defaultAction();
}
function accountRemoveHandle() {
  productRef.value.defaultAction();
}

onBeforeMount(async () => {
  const { mdmName, accountCode, adgroupId, batchId } = route.query;
  // 如果存在广告id，则拉广告
  if (adgroupId) {
    // console.log('dsdsd');
    getAdv(route.query.adgroupId)
  } else {
    // 创建空广告
    store.commit('adv/CREATE_ADV_MODAL');
    store.commit('adv/UPDATE_ADV', {
      batchId
    })
    // 如果存在账号主体 默认创建带有账号的空广告，否则直接创建空广告
    if (mdmName) {
      const accountCodes = accountCode ? (accountCode as string).split(',') : [];
      const accounts = accountCodes.map(accountCode => {
        return new Account({
          accountCode,
          mdmName
        });
      });
      store.commit('adv/UPDATE_ACCOUNTS', accounts);

      await store.dispatch('adv/getCreativeTemplateList');
      store.commit('adv/SET_NORMAL_CREATIVE')
      nextTick(() => {
        productRef.value.defaultAction();
        advDiectRef.value.defaultAction();
      })
    }
  }
})
function targetTypeChange(options: any = {}) {
  const { mode, adgroupId } = options;
  if (mode == 2) {
    quoteAdv(adgroupId);
  } else {
    store.commit('adv/CREATE_ADV_MODAL', {
      retain_id: true
    });
    nextTick(() => {
      advPositionRef.value.defaultAction();
    })


  }
}
async function getAdv(id: any) {
  // 获取广告详情
  await store.dispatch('adv/getAdvDetail', {
    adgroupId: id,
  });
  // console.log('get');
  // 注册页面权限
  store.commit('adv/CONFIG_AUTH', {
    // 账号不可操作
    account: {
      operation: false,
    }
  });
  // 模块回显
  advPositionRef.value.getBackDisplay()
  productRef.value && productRef.value.getBackDisplay();
  advDiectRef.value.getBackDisplay();
  loadPageRef.value.getBackDisplay();

}
async function quoteAdv(id: any) {
  const batchId = adv.value.batchId;
  const adgroupId = adv.value.adgroupId;
  await getAdv(id);
  const name = useAdgroupname(store.state.adv);
  store.commit('adv/UPDATE_ADV', {
    adgroupId,
    batchId,
    adgroupName: name
  })
  // 更新创建类型为`引用已有广告`
  store.commit('adv/UPDATE_ADV_TARGET_VALUE', {
    path: ['market'],
    value: 2,
    key: 'mode'
  });


}


onBeforeRouteLeave(() => {
  // store.dispatch('intelligent/resetData')
})


/*
 * 保存广告信息
 * */
async function handleSave() {

  await accountSelectRef.value.validate();
  console.log('accountSelectRef')
  await productRef.value ? productRef.value.validate() : null;
  if (productRef.value) {
    await productRef.value.validate();
  }
  console.log('productRef')
  await advDiectRef.value.validate();
  console.log('advDiectRef')
  await schedulePriceRef.value.validate();
  console.log('schedulePriceRef')
  if (creativeContentRef.value) {
    await creativeContentRef.value.validate();
  }

  console.log('creativeContentRef')
  await markComponentRef.value.validate();
  console.log('markComponentRef')
  // await loadPageRef.value ? loadPageRef.value.validate() : null;
  if (loadPageRef.value) {
    await loadPageRef.value.validate()
  }
  console.log('loadPageRef')
  saveLoading.value = true;
  const advBody = createAdvBody(store.state.adv);
  console.log('advBody')
  try {
    await saveAdv(advBody);
    message.success('广告创建成功！');

    router.push({
      name: 'IntelCreateList',
      query: {
        batchId: advBody.batchId
      }
    });
  } finally {
    saveLoading.value = false;
  }




}
// 返回
function handleBack() {
  router.back()
}
</script>

<style lang="scss">
.adv-create-form {

  .form-item-label {
    padding-left: 2px;
    padding-bottom: 6px;
  }

  .n-form-item-label__text,
  .form-item-label__text {
    color: rgba(38, 38, 41, 1);
    font-size: 14px;
    line-height: 22px;
    font-weight: bold;

  }

  .n-input,
  .n-select {
    max-width: 480px;
  }
}
</style>
